package com.aaa.rabbitmq.listener;




import com.aaa.entity.PMS_Product;
import com.aaa.mapper.PMS_ProductMapper;
import com.aaa.rabbitmq.RabbitMQConfig;
import com.aaa.service.PMS_ProductService;
import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

/**
 * 消费者：监听队列，从队列中获取消息，并处理消息
 */
@Component
@Slf4j
public class DirectListener {

    @Resource
    PMS_ProductMapper pms_productMapper;

    @Resource
    RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = RabbitMQConfig.DEAD_PMS_PRODUCT_QUEUE)
    public void handleMyQueue(PMS_Product msg, Message message, Channel channel) throws IOException{
        log.info(">>>>>>>>>>过期时间");
        Integer aid=msg.getId();
        //获取活动的有效信息
       PMS_Product validMsg=pms_productMapper.selectPms(aid);
       if (msg.isStart() && validMsg.getPromotionState()==1){
           validMsg.setPromotionState(2);
           pms_productMapper.pmsproductupdatestate2(validMsg.getId());
           //结束时间
           validMsg.setStart(false);
           rabbitTemplate.convertAndSend(RabbitMQConfig.PMS_PRODUCT_QUEUE,validMsg, messages -> {
               //获取过期时间promotionStartTime
               Long expirationTime= validMsg.getPromotionEndTime().getTime() - new Date().getTime();
               log.info(">>>过期"+expirationTime);
               MessageProperties properties = message.getMessageProperties();
               properties.setExpiration(expirationTime.toString());
               return message;
           });
       }else{
           System.out.println("结束");
           validMsg.setPromotionState(3);
           pms_productMapper.pmsproductupdatestate3(validMsg.getId());
       }
        //手动应答
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
    }
}
